import { Button, Form, Popup, Space, PullToRefresh, InfiniteScroll, SpinLoading, Input, Toast } from 'antd-mobile'
import { useCallback, useEffect, useMemo, useState } from 'react'
import PageComponent from '@components/pageComponent'
import PageEmpty from '@components/pageEmpty'
import style from './index.module.less'
import { getArbitrators } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import classNames from 'classnames'
import Selector from '@components/selector'
import Dictionary from '@src/assets/js/dictionary'

const { Item, useForm } = Form

async function getData (current, formData, list, setList, setTotal, setLoading) {
  setLoading(true)
  const condition = getCondition(formData)
  const [e, d] = await awaitWrap(getArbitrators(current, condition))
  setLoading(false)
  if (e === null && d !== null) {
    setTotal(d.total)
    setList([...list, ...d.list])
  }
}

function getCondition (d) {
  const r = []
  if (!d) {
    return r
  }
  if (d.name) {
    r.push({ k: 'name', o: 'like', v: `%${d.name}%` })
  }
  if (d.area) {
    r.push({ k: 'area', o: 'like', v: `%${d.area}%` })
  }
  if (d.gender) {
    r.push({ k: 'gender', o: 'like', v: `%${d.gender}%` })
  }
  if (d.cause_action) {
    r.push({ k: 'cause_action', o: 'like', v: `%${d.cause_action}%` })
  }
  if (d.occupation) {
    r.push({ k: 'occupation', o: 'like', v: `%${d.occupation}%` })
  }
  return r
}

function Line ({ data, current, onClick }) {
  return (
    <div className={classNames(style.line, {[style.active]: data === current})} onClick={() => {
      onClick(data)
    }}>
      <div className={style.name}>{data.name}</div>
      <div className={style.info}>
        <span className={style['info-cell']}>
          <span className={style['info-label']}>职业分类</span>
          <span className={style['info-text']}>{data.occupation}</span>
        </span>
        <span className={style['info-cell']}>
          <span className={style['info-label']}>性别</span>
          <span className={style['info-text']}>{data.gender}</span>
        </span>
        <span className={style['info-cell']}>
          <span className={style['info-label']}>所在区域</span>
          <span className={style['info-text']}>{data.area}</span>
        </span>
      </div>
      {data.cause_action && (
        <div className={style.info}>
          <span className={style['info-label']}>擅长专业</span>
          <span className={style['info-text']}>{data.cause_action}</span>
        </div>
      )}
    </div>
  )
}

function Inner ({ value, onChange, visible, setVisible }) {
  const [formRef] = useForm()
  const [list, setList] = useState([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [searchVisible, setSearchVisible] = useState(false)
  const [formData, setFormData] = useState({})
  const [current, setCurrent] = useState(null)
  const [options1, setOptions1] = useState([])
  const [options2, setOptions2] = useState([])
  const hasMore = useMemo(() => {
      return list.length < total
    }, [total, list])
  const loadMore = useCallback(async () => {
      await getData(Math.ceil(list.length / 20) + 1, formData, list, setList, setTotal, setLoading)
    }, [list, formData])
  useEffect(() => {
    getData(1, {}, [], setList, setTotal, setLoading)
    const d = new Dictionary()
    d.init('仲裁员职业分类（对外）,专业')
      .then(() => {
        setOptions1(d.getList('仲裁员职业分类（对外）').map(li => li.title))
        setOptions2(d.getList('专业').map(li => li.title))
      })
  }, [])
  return (
    <>
      <div className={style.value}>
        <div className={style['value-text']}>{value ? value.name : ''}</div>
      </div>
      <Popup
        bodyStyle={{ width: '100vw' }}
        position='right'
        visible={visible}
        onClose={() => setVisible(false)}
        mask={false}
      >
        <PageComponent
          title='仲裁员选择'
          onBack={() => setVisible(false)}
          right={<a className={style.search} onClick={() => { setSearchVisible(true) }}>修改查询条件</a>}
        >
          <div className={style.container}>
            <div className={style.body}>
              <div className={style.inner}>
                <PullToRefresh
                  onRefresh={async () => {
                    setList([])
                    await getData(1, {}, [], setList, setTotal, setLoading)
                  }}
                >
                  {loading && list.length === 0 && (
                    <div className={style.loading}>
                      <SpinLoading />
                    </div>
                  )}
                  {
                    !loading && list.length === 0 && (
                      <PageEmpty />
                    )
                  }
                  {
                    list.map(li => {
                      return (
                        <Line data={li} key={li.id} current={current} onClick={(v) => setCurrent(v)} />
                      )
                    })
                  }
                  {
                    list.length > 0 && <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
                  }
                </PullToRefresh>
              </div>
            </div>
            <div className={style.operate}>
              <span className={style.selected}>
                <span className={style['selected-label']}>当前选中</span>
                <span className={style['selected-person']}>
                  <span className={style['selected-person-text']}>
                    {current ? current.name : '无'}
                  </span>
                </span>
              </span>
              <div className={style.btns}>
                <Space>
                  <Button onClick={() => {
                    setVisible(false)
                  }}>取消</Button>
                  <Button className={style.ghost} onClick={() => {
                    onChange({ id: '', name: '委托主任指定' })
                    setVisible(false)
                  }}>委托主任选定</Button>
                  <Button color='primary' onClick={() => {
                    onChange(current)
                    setVisible(false)
                  }}>确定</Button>
                </Space>
              </div>
            </div>
          </div>
          <Popup
            bodyStyle={{ width: '80vw' }}
            position='right'
            visible={searchVisible}
            onMaskClick={() => { setSearchVisible(false) }}
          >
            <Form form={formRef} layout='horizontal' onFinish={d => {
              setFormData(d)
              getData(1, d, [], setList, setTotal, setLoading)
              setSearchVisible(false)
            }}>
              <Item label='姓名' name='name'>
                <Input placeholder='请输入' clearable />
              </Item>
              <Item label='所属区域' name='area'>
                <Input placeholder='请输入' clearable />
              </Item>
              <Selector label='性别' name='gender' options={['男', '女']} formRef={formRef} />
              <Selector label='职业' name='occupation' options={options1} formRef={formRef} />
              <Selector label='专业' name='cause_action' options={options2} formRef={formRef} />
              <Item>
                <div className={style['form-btns']}>
                  <Space>
                    <Button type='button' onClick={() => { formRef.resetFields() }}>重置</Button>
                    <Button type='submit' color='primary'>确定</Button>
                  </Space>
                </div>
              </Item>
            </Form>
          </Popup>
        </PageComponent>
      </Popup>
    </>
  )
}

function Main ({ label, name, rules, disabled }) {
  const [visible, setVisible] = useState(false)
  return (
    <Item
      label={label}
      name={name}
      rules={rules}
      disabled={disabled}
      onClick={() => { setVisible(true) }}
    >
      <Inner visible={visible} setVisible={setVisible} />
    </Item>
  )
}

export default Main
